import * as React from 'react'

interface IKeyEvent {
  keyCode: number;
}

interface Iprops {
  onAdd: (val?: string) => void;
}

class TodoInput extends React.Component<Iprops> {
  // 在react ts 中获取ref
  private input:React.RefObject<HTMLInputElement>
  constructor(props:Iprops) {
    super(props);
    this.input = React.createRef();
  }
  public render() {
    return (
      <div className="todo__input--wrapper">
        <input
          type="text"
          className="todo__input"
          ref={this.input}
          onKeyUp={this.addItemByKey}
        />
        <button onClick={this.addTodoItem}>add todo</button>
      </div>
    )
  }
  public addTodoItem = () => {
    const oInput = this.input.current;
    if (oInput && oInput.value) {
      this.props.onAdd(oInput.value);
      oInput.value = '';
    }
  }
  public addItemByKey = (ev: IKeyEvent) => {
    if (ev.keyCode === 13) {
      this.addTodoItem();
    }
  }
}

export default TodoInput